#include "hashage.hpp"

int hash(string v,int M)
{
  int i(0),h(0),a(127);

  while(v[i] != '\0')
    {
      h=(a*h+v[i])%M;
      ++i;
    }

  return h;
}

void create_hash(chained_index hash_tab[])
{
  for(int i=0 ; i < TAILLE_HASH ; ++i)
    hash_tab[i]=NULL;
}

void initialisation_hash(chained_index hash_tab[],chained_index &c_i)
{
  int ref;
  chained_index tmp;

  while(c_i != NULL)
    {
      ref=hash(c_i->word,TAILLE_HASH);

      tmp=c_i;
      c_i=c_i->next;
      tmp->next=NULL;

      if(hash_tab[ref] == NULL)
	{
	  hash_tab[ref]=tmp;
	}
      else
	{
	  chained_index lecture=hash_tab[ref];

	  while(lecture->next != NULL)
	    lecture=lecture->next;

	  lecture->next=tmp;
	}
    }
}

void affiche_hash(const chained_index hash_tab[])
{
  for(int i=0 ; i < TAILLE_HASH ; ++i)
    {
      if(hash_tab[i] != NULL)
	{
	  cout << "i = " << i << endl;
	  affiche_index(hash_tab[i]);
	}
      else
	{
	  cout << "i = " << i << endl;
	  cout << "NULL" << endl;
	}
    }
}

void delete_all_hash(chained_index hash_tab[])
{
  for(int i=0 ; i < TAILLE_HASH ; ++i)
    delete_all_index(hash_tab[i]);
}

void add_ligne_hash(chained_index hash_tab[],chained_word & c_w)
{
  int ligne(0),ref;
  string word("");
  chained_word tmp;
  chained_index lecture_index;

  while(c_w != NULL)
    {
      word=c_w->word;
      ligne=c_w->cpt;
      cout << "LIGNE " << ligne << " WORD " << word << endl;

      ref=hash(word,TAILLE_HASH);
      lecture_index=hash_tab[ref];

      while(lecture_index != NULL && lecture_index->word != word)
	lecture_index=lecture_index->next;

      if(lecture_index != NULL)
	{
	  cout << word << endl << endl;
	  add_number_ligne(lecture_index,word,ligne);
	}

      tmp=c_w;
      c_w=c_w->next;
      delete_word(tmp);
    }
}
